#include <UnitTest++.h>
#include "main.h"
#include <sys/stat.h>
#include <iostream>
#include <stdarg.h>
#include <sstream>
#include <map>
#include "mock_file.h"
#include "testable_engine.h"
#include "sample_data.h"

SUITE(err_suite) {
    
    TEST(throws_fatal_error) {
        CHECK_THROW(err("Resistance is futile."), FatalError);
    }
}

SUITE(MiscSetup_suite) {
    TEST(allocates_strbuf) {
        CHECK(!strbuf);
        MiscSetup();
        
        CHECK(strbuf);
        MiscShutdown();
    }
}

using namespace VERGE1;

SUITE(InitPartyStats_suite) {

    TEST(fails_when_party_dat_does_not_exist) {
        try {
            MiscSetup();
            testable_engine.remove("PARTY.DAT");
            testable_engine.InitPartyStats();
            CHECK(false);
        } catch (FatalError exc) {
            CHECK_EQUAL(exc.getMessage(), "Fatal error: PARTY.DAT not found");
        }
    }
    
    TEST(succeeds_when_party_dat_exists) {
        MiscSetup();
        File* file = 0;

        try {
            sample_data_list_t::iterator iter;
            
            BlimpoWarrior::create_sample_data();
            
            iter = BlimpoWarrior::sample_files.begin();
            for (; iter != BlimpoWarrior::sample_files.end(); ++iter) {
                std::string filename = iter->first;
                const char* sample_data = iter->second;

                file = testable_engine.fopen(filename.c_str(), "w");
                if (!file) {
                    std::string message = "Couldn't create " + filename; 
                    err(message.c_str());
                }
                testable_engine.fwrite(sample_data, 1, strlen(sample_data), file);
                testable_engine.fclose(file);
            }
            
            testable_engine.InitPartyStats();

            iter = BlimpoWarrior::sample_files.begin();
            for (; iter != BlimpoWarrior::sample_files.end(); ++iter) {
                std::string filename = iter->first;
                testable_engine.remove(filename.c_str());
            }

        } catch (VERGE1_Exception exc) {
            std::cout << exc.getMessage() << std::endl;
            CHECK(false);
        }
    }
}
